<template>
  <div class="loginPage">
    <div class="pageMb">
      <div class="loginCon">
        <img src="../../assets/images/gjlogo.png" alt="">
        <p>{{ titleText }}</p>
        <el-tabs v-if="loginPage" v-model="activeName" stretch>
          <el-tab-pane label="账号登录" name="account">
            <el-form
              ref="account"
              :model="formData"
              :rules="rules"
            >
              <el-form-item prop="username">
                <el-input
                  v-model="formData.username"
                  type="text"
                  autocomplete="on"
                  placeholder="请输入用户名"
                  clearable
                >
                  <i slot="prefix" class="el-input__icon el-icon-user" />
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  v-model="formData.password"
                  type="password"
                  autocomplete="on"
                  placeholder="请输入用户密码"
                  clearable
                >
                  <i slot="prefix" class="el-input__icon el-icon-lock" />
                </el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="手机登录" name="phone">
            <el-form
              ref="phone"
              :model="phoneForm"
              :rules="phoneRules"
            >
              <el-form-item prop="phoneNum">
                <el-input
                  v-model="phoneForm.phoneNum"
                  type="text"
                  autocomplete="on"
                  placeholder="请输入手机号"
                  clearable
                >
                  <i slot="prefix" class="el-input__icon el-icon-phone-outline" />
                </el-input>
              </el-form-item>
              <el-row>
                <el-col :span="14" style="padding:0px;margin:0px">
                  <el-form-item prop="message" class="validateInput">
                    <el-input
                      v-model="phoneForm.message"
                      type="text"
                      autocomplete="on"
                      placeholder="请输入验证码"
                      clearable
                    >
                      <i slot="prefix" class="el-input__icon el-icon-message" />
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-button
                    type="primary"
                    class="validateBtn"
                    :disabled="btnFlag"
                    @click="sendMessage"
                  >
                    {{ btnText }}
                  </el-button>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <div v-if="loginPage" class="bottomBtn">
          <el-button type="primary" round @click="submitLogin(activeName)">
            登录
          </el-button><br>
          <span class="goReg" @click="loginPage=false"> 前往注册 <i class="el-icon-right" /></span>
        </div>
        <register-view v-if="!loginPage" :goback="goback" />
      </div>
    </div>
  </div>
</template>
<script>
import RegisterView from './RegisterView';
import { login, checkUserPhone, sendMessageCode, getInfoByPhone } from '@/api/user';
export default {
  components: { RegisterView },
  data() {
    var validateUser = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账号'));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码'));
      } else if (!(/^[1][3,4,5,7,8,9][0-9]{9}$/.test(value))) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        checkUserPhone(value).then(res => {
          if (res.data.code !== 200) {
            callback(new Error('该手机号未注册，请先注册'));
          } else {
            callback();
          }
        });
      }
    };
    var validateMessage = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'));
      } else {
        callback();
      }
    };
    return {
      activeName: 'account',
      formData: {
        username: '',
        password: ''
      },
      phoneForm: {
        phoneNum: '',
        message: ''
      },
      rules: {
        username: [
          { validator: validateUser, trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ]
      },
      phoneRules: {
        phoneNum: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        message: [
          { validator: validateMessage, trigger: 'blur' }
        ]
      },
      btnFlag: false,
      btnText: '验证码',
      timer: null,
      loginPage: true,
      getMessage: {}
    };
  },
  computed: {
    titleText() {
      if (this.loginPage) {
        return '想你所想，杠你所杠！';
      } else {
        return '人人笑杠精，人人皆是杠精！';
      }
    }
  },
  created() {},
  mounted() {},
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    // 发送验证码
    sendMessage() {
      this.$refs['phone'].validateField('phoneNum', (valid) => {
        if (!valid) {
          sendMessageCode({ 'phoneNum': this.phoneForm.phoneNum }).then(res => {
            if (res.data.code === 200) {
              this.$message({
                showClose: true,
                message: '发送成功',
                type: 'success'
              });
              this.getMessage = res.data.data;
              this.btnFlag = true;
              var DataNum = 60;
              this.btnText = '(60)秒';
              this.timer = setInterval(() => {
                DataNum--;
                this.btnText = `(${DataNum})秒`;
                if (DataNum === 0) {
                  clearInterval(this.timer);
                  this.btnFlag = false;
                  this.btnText = '验证码';
                }
              }, 1000);
            } else {
              this.$message({
                showClose: true,
                message: '发送失败',
                type: 'error'
              });
            }
          }).catch(() => {
            this.$message({
              showClose: true,
              message: '发送失败',
              type: 'error'
            });
          });
        } else {
          return false;
        }
      });
    },
    // 返回登录
    goback() {
      this.loginPage = true;
    },
    // 登录
    submitLogin(refName) {
      const params = {
        'userName': this.formData.username,
        'password': this.formData.password
      };
      this.$refs[refName].validate((valid) => {
        if (valid) {
          if (refName === 'phone') {
            console.log(this.getMessage, this.phoneForm);
            if (this.getMessage.phone === this.phoneForm.phoneNum && this.getMessage.code === parseInt(this.phoneForm.message)) {
              const da = { userPhone: this.getMessage.phone };
              getInfoByPhone(da).then(res => {
                this.$store.dispatch('setUserInfo', res.data.data);
                this.$router.push({ path: '/home' });
              });
            } else {
              this.$message({
                showClose: true,
                message: '手机或验证码错误',
                type: 'error'
              });
            }
            return;
          }
          login(params).then(res => {
            if (res.data.code === 200) {
              // console.log(res.data.data);
              this.$store.dispatch('setUserInfo', res.data.data);
              const userInfo = {
                name: res.data.data.userName,
                exper: res.data.data.userexper,
                date: res.data.data.addDate
              };
              sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
              this.$router.push({ path: '/home' });
            } else {
              this.$message({
                showClose: true,
                message: '用户或密码错误',
                type: 'error'
              });
            }
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style lang="scss">
.loginPage{
  width: 100%;
  height: calc(100vh);
  padding: 0px;
  margin: 0px;
  background-image: url('../../assets/images/bj.jpeg');
  background-size: cover;
  .pageMb{
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.4);
    display: flex;
    justify-content: center;
    align-items: center;
    .loginCon{
      width: 75%;
      // height: 600px;
      text-align: center;
      border-radius: 5px;
      background: rgba(0, 0, 0, .6);
      box-shadow: 3px 3px 6px 3px rgba(0, 0, 0, .3);
      padding: 20px;
      p{
        font-size: 14px;
        color: #fff;
        margin: 15px 0px;
        font-weight: 600;
      }
      .el-input__inner{
        border-radius: 20px;
      }
      .validateBtn{
        width: 100%;
        height: 40px;
        border-radius: 0px 20px 20px 0px;
      }
      .validateInput{
        .el-input__inner{
          border-radius: 20px 0px 0px 20px;
        }
      }
      .bottomBtn{
        width: 100%;
        .el-button{
          width: 100%;
          margin-bottom: 10px;
        }
        .goReg{
          font-size: 12px;
          color: #fff;
        }
        .goReg:hover{
          color: #409EFF;
        }
      }
    }
  }
}
</style>
